import Vue from 'vue'
import {siblings} from '../scripts/until'

Vue.directive('drag', {
    bind: function (el, binding) {
        el.onmousedown = function (e) {
            let disX = e.clientX - el.offsetLeft;
            let disY = e.clientY - el.offsetTop;
            let parEl = el.parentNode;
            let offX = el.offsetLeft;
            let offY = el.offsetTop;
            el.classList.remove('ease-move');
            document.onmousemove = function (e) {
                el.style.zIndex = 3;
                siblings(el).forEach(function(value, index, array) {
                    value.style.opacity = 0.4;
                })
                let l = e.clientX - disX;
                let t = e.clientY - disY;
                // 不超出父元素
                // if (l < 3) {
                //     el.style.left = 0;
                //     return;
                // }
                // if (l > (parEl.offsetWidth - el.offsetWidth - 3)) {
                //     el.style.left = parEl.offsetWidth - el.offsetWidth + 'px';
                //     return;
                // }
                // if (t < 3) {
                //     el.style.top = 0;
                //     return;
                // }
                // if (t > (parEl.offsetHeight - el.offsetHeight - 3)) {
                //     el.style.top = parEl.offsetHeight - el.offsetHeight + 'px';
                //     return;
                // }
                el.style.left = l + 'px';
                el.style.top = t + 'px';
            };
            document.onmouseup = function (e) {
                document.onmousemove = null;
                document.onmouseup = null;
                el.style.zIndex = null;
                el.classList.add('ease-move');
                siblings(el).forEach(function(value, index, array) {
                    value.style.opacity = 1;
                })
                binding.value({
                    el: el,
                    left: el.offsetLeft,
                    top: el.offsetTop,
                    xChange: el.offsetLeft - offX,
                    yChange: el.offsetTop - offY,
                    xOrigin: offX,
                    yOrigin: offY
                })
            };
        };
    }
});